


use clap::Args;
use serde::{Deserialize, Serialize};
use wtask_base::{app::{get_wtask_result_dir, get_wtask_data_dir}, error::WResult};

use crate::{task::utils::meta::{CmdList, CmdMeta, TASK_RUN_LOG_END, TASK_RUN_LOG_PREFIX, TaskStatus}, utils::AppTrait};




#[derive(Debug, Clone, Serialize, Deserialize, Args)]
pub struct AppTaskResult {
    /// 筛选任务状态
    #[arg(value_enum)]
    pub(crate) status: Option<TaskStatus>,

    /// 筛选任务ID
    #[arg(long)]
    pub(crate) id: Option<String>,
}


impl AppTrait for AppTaskResult {
    type Status = ();
    type Res = CmdList;
    
    async fn server_handle_single(self) -> WResult<CmdList> {
        let dir_task = get_wtask_data_dir("result", false)?;
        
        let meta_paths = if let Some(id) = &self.id  {
            let dir_task = get_wtask_result_dir(id)?;
            if let Some(dir_task) = dir_task {
                vec![dir_task]
            } else {
                Vec::with_capacity(0)
            }
        } else {
            dir_task.read_dir()?
            .flat_map(| v | {
                v.unwrap().path().read_dir().unwrap().map(| v | {
                    v.unwrap().path()
                })
            })
            .filter(| v | {
                if let Some(status) = &self.status {
                    v.join(format!("{}{:?}{}", TASK_RUN_LOG_PREFIX, status, TASK_RUN_LOG_END)).exists()
                } else {
                    true
                }
            })
            .collect::<Vec<_>>()
        };
        let mut metas = meta_paths.into_iter().map(| v | {
            CmdMeta::load_from_dir(&v).unwrap()
        }).collect::<Vec<_>>();
        metas.sort_by_key(| v | v.time_create);
        metas.reverse();
        Ok(CmdList {
            status: self.status,
            metas
        })
    }
}
